<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="工单编号" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题描述" prop="problemDescription">
        <el-input
          v-model="queryParams.problemDescription"
          placeholder="请输入问题描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="已关闭" value="CLOSED" />
          <el-option label="处理中" value="IN_PROGRESS" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['system:order:remove']"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="orderNum" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="问题描述" align="center" prop="problemDescription" />
      <el-table-column label="问题类型" align="center">
        <template slot-scope="scope">
          {{ getProblemType(scope.row.problemType) }}
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 'IN_PROGRESS' ? 'error' : 'info'">
            {{ scope.row.status == "IN_PROGRESS" ? "处理中" : "已关闭" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div style="padding-top: 10px">
            <el-badge
              :value="scope.row.unReadNum"
              :hidden="scope.row.unReadNum == 0"
              class="item"
            >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:order:edit']"
              >
                回复
              </el-button>
            </el-badge>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:order:remove']"
              style="margin-left: 20px"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.params.pageNum"
      :limit.sync="queryParams.params.pageSize"
      @pagination="getList"
    />

    <!-- 回复工单对话框 -->
    <el-dialog title="回复工单" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单编号" prop="orderNum">
          {{ form.orderNum }}
          <el-tag :type="form.status == 'IN_PROGRESS' ? 'error' : 'info'">
            {{ form.status == "IN_PROGRESS" ? "处理中" : "已关闭" }}
          </el-tag>
        </el-form-item>
        <el-form-item label="问题描述" prop="problemDescription">
          {{ form.problemDescription }}
        </el-form-item>
        <el-form-item label="消息">
          <div id="chatBox" class="chat-box">
            <div
              v-for="(item, index) in form.list"
              :key="index"
              class="chat-item"
              :class="item.userType == '00' ? 'right' : 'left'"
            >
              <el-image
                style="width: 50px; height: 50px; border-radius: 4px"
                :src="filterAvatar(item)"
              />
              <div class="chat-row">
                <div class="time">
                  {{ item.createTime || "" }}
                </div>
                <div class="chat-msg">
                  <template v-if="item.contentType == 2">
                    <el-image
                      style="width: 200px; height: 200px"
                      :src="baseUrl + item.content"
                    />
                  </template>
                  <template v-else>
                    {{ item.content || "-" }}
                  </template>
                </div>
              </div>
            </div>
          </div>
          <div class="chat-input">
            <el-input
              type="textarea"
              v-model="repaly"
              :autosize="{
                minRows: 2,
                maxRows: 3,
              }"
              :disabled="disabled"
              :maxlength="300"
              show-word-limit
              placeholder="请输入回复内容"
            />
            <div class="flex" :class="{ disabled: disabled }">
              <div>
                <File-upload
                  v-if="!disabled"
                  v-model="repalyImage"
                  :limit="1"
                  :fileType="['png', 'jpg', 'jpeg']"
                  label="图片"
                  :isShowTip="false"
                />
              </div>
              <el-button type="text" :disabled="disabled" @click="handleSend(1)">
                发送
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addMsg } from "@/api/system/order";
import defaultImg1 from "@/assets/images/default.png";
import defaultImg2 from "@/assets/images/defaultImg2.png";
export default {
  name: "Order",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      loading: false, // 遮罩层
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      dataList: [], // 工单表格数据
      open: false, // 是否显示弹出层
      // 查询参数
      queryParams: {
        params: {
          pageNum: 1,
          pageSize: 10,
        },
        orderNum: null,
        problemDescription: null,
      },
      form: {}, // 表单参数
      // 表单校验
      rules: {},
      typeList: [
        // 问题类型
        { value: 1, label: "售后问题" },
        { value: 2, label: "产品问题" },
      ],
      disabled: false, // 是否禁用
      repaly: "", // 回复内容
      repalyImage: "", // 回复图片
      pageNum: 1,
      pageSize: 10,
      msgTotal: 0, // 消息总数
      isFrist: true,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    repalyImage(v) {
      if (v) {
        this.handleSend(2);
      }
    },
    open(v) {
      if (!v) {
        this.repaly = "";
        this.repalyImage = "";
        this.pageNum = 1;
        this.pageSize = 10;
        this.msgTotal = 0;
        this.isFrist = true;
        this.getList();
      }
    },
  },
  methods: {
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 头像处理
    filterAvatar(val) {
      if (val.avatar.indexOf("http") > -1) {
        return val.avatar;
      } else if (val.avatar.indexOf("profile") > -1) {
        return this.baseUrl + val.avatar;
      } else {
        return val.userType == "00" ? defaultImg2 : defaultImg1;
      }
    },

    // 表单重置
    reset() {
      this.form = {
        orderNum: null,
        problemDescription: null,
        problemType: null,
        status: null,
        list: [],
      };
      this.resetForm("form");
    },

    // 回复消息
    handleSend(type = 1) {
      if (type == 1 && this.repaly == "") {
        this.$modal.msgError("请输入回复内容");
        return;
      }
      let data = {
        orderNum: this.form.orderNum,
        content: type == 1 ? this.repaly : this.repalyImage,
        contentType: type,
      };
      addMsg(data).then((res) => {
        this.$modal.msgSuccess("回复成功");
        if (type == 1) {
          this.repaly = "";
        } else {
          this.repalyImage = "";
        }
        this.handleUpdate(this.form);
      });
    },

    // 获取问题类型
    getProblemType(val) {
      let row = this.typeList.find((i) => i.value == val);
      return row ? row.label : null;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.params.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderNum);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      console.log(selection, "多选id");
    },

    /** 回复按钮操作 */
    handleUpdate(row) {
      this.form = Object.assign({}, row);
      this.disabled = row.status != "IN_PROGRESS";
      this.getMsgList();
    },

    // 获取消息列表
    getMsgList() {
      getOrder({
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        },
        orderNum: this.form.orderNum,
        unReadNum: this.form.unReadNum,
      }).then((res) => {
        if (this.pageNum == 1) {
          this.form.list = res.rows;
          this.dataList.forEach((i) => {
            if (i.orderNum == this.form.orderNum) i.unReadNum = 0;
          });
        } else {
          this.form.list = res.rows.concat(this.form.list);
          this.$forceUpdate();
        }
        this.msgTotal = res.total;
        this.open = true;
        if (this.isFrist) {
          this.isFrist = false;
          setTimeout(() => {
            let scrollBox = document.querySelector(".chat-box");
            scrollBox.scrollTop = scrollBox.scrollHeight;
            scrollBox.addEventListener("scroll", (e) => {
              if (e.target.scrollTop == 0) {
                if (this.msgTotal > this.form.list.length) {
                  this.pageNum++;
                  this.getMsgList();
                }
              }
            });
          }, 0);
        } else {
          setTimeout(() => {
            let scrollBox = document.querySelector(".chat-box");
            scrollBox.scrollTop = scrollBox.scrollHeight;
          }, 0);
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const orderNums = row ? [row.orderNum] : this.ids;
      this.$modal
        .confirm('是否确认删除工单编号为"' + orderNums + '"的数据项？')
        .then(() => {
          delOrder(orderNums).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.chat-box {
  min-height: 120px;
  max-height: 400px;
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  scroll-behavior: smooth;
  .chat-item {
    display: flex;
    margin-bottom: 20px;
    .el-image {
      margin-top: 30px;
    }
    .chat-row {
      max-width: calc(100% - 100px);
      display: flex;
      flex-direction: column;
    }
    .chat-msg {
      background: #f2f6fc;
      padding: 8px 20px;
      border-radius: 8px;
      position: relative;
      &::after,
      &::before {
        display: none;
        content: "";
        width: 0;
        height: 0;
        border-top: 6px solid transparent;
        border-bottom: 6px solid transparent;
        position: absolute;
        top: 10px;
      }
    }
    .time {
      height: 30px;
      color: #ccc;
    }
  }
  .left {
    justify-content: flex-start;
    .chat-row {
      align-items: flex-start;
    }
    .chat-msg {
      margin-left: 10px;
      &::before {
        display: block;
        border-right: 6px solid #f2f6fc;
        left: -6px;
      }
    }
    .time {
      margin-left: 10px;
      text-align: left;
    }
  }
  .right {
    flex-direction: row-reverse;
    .chat-row {
      align-items: flex-end;
    }
    .chat-msg {
      margin-right: 10px;
      &::after {
        display: block;
        border-left: 6px solid #f2f6fc;
        right: -6px;
      }
    }
    .time {
      text-align: right;
      margin-right: 10px;
    }
  }
}
::v-deep .el-textarea__inner {
  overflow-y: auto;

  border: none;
  resize: none;
}
.chat-input {
  border: 1px solid #ebeef5;
  .flex {
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
  }
  .disabled {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
  }
}
</style>
